<?php

/**
 * As soon as the current URL does not fit the URL at $_SESSION['s_serverurl'] this function is called
 * - check if there is a session for the new URL -> no = timeout
 * - make a backup of the previous session information
 * - copy information from new URL session to current session files
 *
 * URL is not set directly at the array - md5() of the URL is used
 *
 * @param String $new_url New URL which was opened
 * @return false if the new URL is not at our session buffer; else true
 */
function swap_session($new_url) {
	$new_url = str_replace("secret/","",$new_url);

	$url_hash_new = md5($new_url);

	if (!isset($_SESSION[$url_hash_new])) {
		// we do not know the session where we want to restore from
		return false;
	}

	if (isset($_SESSION['s_serverurl']) && isset($_SESSION['s_auth'])) {
		// the other session may have been destroyed due to logout
		$url_hash = md5($_SESSION['s_serverurl']);
		// backup current values (overwrite or create)
		$_SESSION[$url_hash]['lang']                = $_SESSION['lang'];
		$_SESSION[$url_hash]['s_loggedin']          = $_SESSION['s_loggedin'];
		$_SESSION[$url_hash]['s_auth']              = $_SESSION['s_auth'];
		$_SESSION[$url_hash]['s_galaxyview_galaxy'] = isset($_SESSION['s_galaxyview_galaxy']) ? $_SESSION['s_galaxyview_galaxy'] : 1;
		$_SESSION[$url_hash]['s_galaxyview_system'] = isset($_SESSION['s_galaxyview_system']) ? $_SESSION['s_galaxyview_system'] : 1;
		$_SESSION[$url_hash]['s_serverurl']         = $_SESSION['s_serverurl'];
	} // else old tool (<5.0) -> cannot run proper backup without adjusting the old tool code

	$_SESSION['lang']                = $_SESSION[$url_hash_new]['lang'];
	if (isset($_SESSION[$url_hash_new]['s_auth'])) {

		$_SESSION['s_auth']              = $_SESSION[$url_hash_new]['s_auth'];
		$_SESSION['s_galaxyview_galaxy'] = $_SESSION[$url_hash_new]['s_galaxyview_galaxy'];
		$_SESSION['s_galaxyview_system'] = $_SESSION[$url_hash_new]['s_galaxyview_system'];
	} // else: we switch from an old (< 5.0) tool to a new tool >= 5.0 and keep the variables as they are because they were not replaced via backup at old tool
	$_SESSION['s_loggedin']          = $_SESSION[$url_hash_new]['s_loggedin'];
	$_SESSION['s_serverurl']         = $_SESSION[$url_hash_new]['s_serverurl'];

	return true;
}


/**
 * Logout of current session - so unset session handler array of that URL
 *
 */
function log_out() {
	if (isset($_SESSION['s_serverurl'])) {
		$url_hash = md5($_SESSION['s_serverurl']);
		unset($_SESSION[$url_hash]);
	}
}

?>